import logging
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import socket
import subprocess
import time
import random

# Chrome WebDriver 路径
chrome_driver_path = r"D:\software\python\chromedriver-win64\chromedriver-win64\chromedriver.exe"
chrome_binary_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"

options = Options()
options.add_experimental_option("useAutomationExtension", False)  # 禁用自动化扩展
# temp_edge_driver_path = load_config.config("temp-data", "path")
# options.add_argument(temp_edge_driver_path)  # 自定义用户数据目录
options.add_experimental_option("excludeSwitches", ["enable-automation"])  # 隐藏 "正在受自动化软件控制"
options.add_experimental_option("detach", True)  # 防止浏览器关闭
# 添加一个参数来禁用“AutomationControlled”标志
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("--enable-logging")  # 启用日志
options.add_argument("--v=1")  # 设置日志级别
# 添加一个参数来禁用“AutomationControlled”标志
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("--force-device-scale-factor=1")

# 配置日志类型，启用性能日志
caps = DesiredCapabilities.CHROME
caps['goog:loggingPrefs'] = {'performance': 'ALL'}

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

caps = {}  # 可根据需求设置能力配置


# 检查端口是否已被占用（即 Chrome 是否已经启动）
def is_chrome_running(port=9224):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(('localhost', port))
    sock.close()
    return result == 0


# 启动 Chrome 浏览器并启用远程调试
def start_chrome():
    try:
        if not is_chrome_running():  # 如果 Chrome 没有启动，则启动
            subprocess.Popen([chrome_binary_path, "--remote-debugging-port=9224"], stdout=subprocess.DEVNULL,
                             stderr=subprocess.DEVNULL)
            logging.info("已启动 Google Chrome 浏览器，开启远程调试模式...")
        else:
            logging.info("Google Chrome 浏览器已在运行，跳过启动步骤。")
    except Exception as e:
        logging.error(f"启动 Google Chrome 失败: {e}")


# 配置 ChromeOptions
options = Options()
options.debugger_address = "localhost:9224"  # 连接到已打开的浏览器

# 启动或确保 Chrome 已启动
start_chrome()

# 使用随机时间（1-5秒）替换 sleep(3)
random_sleep_time = random.uniform(1, 2)  # 生成一个 1 到 5 之间的随机浮动时间，精确到毫秒
logging.info(f"等待 {random_sleep_time:.3f} 秒...")  # 打印休眠时间
time.sleep(random_sleep_time)  # 等待随机时间

# 连接到已运行的 Chrome 浏览器
try:
    driver = webdriver.Chrome(service=Service(chrome_driver_path), options=options, desired_capabilities=caps)
    logging.info("成功连接到已打开的 Google Chrome 浏览器")
    time.sleep(3)

    # 获取当前页面的 URL
    current_url = driver.current_url
    current_urls = driver.current_url
    # 最大化窗口并将其置于屏幕中央
    # driver.maximize_window()
    # driver.set_window_position(0, 0)  # 将窗口移动到屏幕左上角

    # 判断是否已登录到目标 URL
    if current_url == "https://www.zhipin.com/web/chat/index" or current_urls == "https://www.zhipin.com/web/chat/recommend":
        logging.info("当前已登录到 boss 账号，不再登录！")
    else:
        logging.info(f"当前页面 URL: {current_url}")
        logging.info("当前未登录到BOSS， 即将跳转BOSS")
        time.sleep(random_sleep_time)
        # 如果不是目标 URL，访问该网址
        # driver.get("https://www.zhipin.com/web/chat/index")
        driver.get("https://www.zhipin.com/web/chat/recommend")
        time.sleep(random_sleep_time)

    # 获取页面标题
    print("当前页面标题:", driver.title)

except Exception as e:
    logging.error(f"连接到已打开的 Google Chrome 浏览器失败: {e}")
    driver = None  # 确保在异常发生时 driver 为 None
